<template>
  <div class="container">
    <!-- 外部header -->
    <div class="container-header">
      <div class="header">
        <p class="header-title">Logged as</p>
        <select v-model="loginUser" @change="changeUser">
          <option value="zhangsan">张三</option>
          <option value="luke">卢克</option>
        </select>
      </div>

      <div class="button-theme">
        <button class="button-light" @click="transformMode('light')"> Light </button>
        <button class="button-dark" @click="transformMode('dark')"> Dark </button>
      </div>
    </div>

    <!-- 聊天组件 -->
    <t-card body-class-name="container-content">
      <div class="room-sider">
        <!-- 左侧头部 -->
        <header class="left-sider-header">
          <t-input placeholder="Search Input" clearable>
            <template #suffixIcon>
              <search-icon :style="{ cursor: 'pointer', 'font-size': '16px' }" />
            </template>
          </t-input>
          <AddCircleFilledIcon @click="createRoom" color="#0052D9"
            :style="{ cursor: 'pointer', 'margin-left': '10px', 'font-size': 20 }" />
        </header>

        <!-- 左侧房间列表 -->
        <main>
          <div class="room-list">

            <RoomItem v-for="item in roomList || []" :key="item.id" :class="{ 'room-selected': selectedId === item.id }"
              @click="selected(item.id)">
            </RoomItem>
          </div>
        </main>
      </div>

      <!-- 右侧房间内容 -->
      <div class="room-input-main">
        <!-- 右侧头部 -->
        <header class="room-input-header">
          <div class="input-header-title">
            <MenuUnfoldIcon :style="{ fontSize: '26px' }" />
            <t-space align="center" :style="{ marginLeft: '10px' }">
              <t-avatar size="42px" image="https://tdesign.gtimg.com/site/avatar.jpg" />
              <div>房间名字</div>
            </t-space>
          </div>

        </header>
        <!-- 右侧内容 -->
        <main class="room-input-history">
          <div class="room-info">
            CREATE AT {{ firstRoomText.timestamp }}
          </div>
          <div class="room-info">
            {{ firstRoomText.message }}
          </div>
          <Message v-for="msg in messageList || []" :key="msg.id" :id="msg.id" :is-me="msg.user.id === loginUser"
            :info="msg.content" :time="msg.timestamp" />
        </main>
        <!-- 右侧输入框 -->
        <footer class="room-input-message">
          <t-input @enter="sendInfo" v-model="info" placeholder="输入信息" class="input-message" />
          <div class="room-input-button">
            <t-space align="center" :size="12">
              <HappyFilledIcon :style="{ fontSize: '20px' }" />
              <SendFilledIcon :style="{ fontSize: '20px' }" />
            </t-space>
          </div>
        </footer>
      </div>
    </t-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { AddCircleFilledIcon, SendFilledIcon, HappyFilledIcon, SearchIcon, MenuUnfoldIcon } from 'tdesign-icons-vue-next';
import { io } from "socket.io-client";
import { LOGIN_USER_LIST, type MESSAGE_TYPE, type ROOM_LIST_TYPE } from "../utlis/common";
import { setSharedRoomInfo, transformMode } from '../utlis/room';
import RoomItem from "./RoomItem.vue";
import Message from "./Message.vue";


const socket = io("http://localhost:3000", {});


const loginUser = ref('zhangsan');

const userInfo = computed(() => {
  return LOGIN_USER_LIST.find(user => user.id === loginUser.value) || null;
})

const connect = ref(false);

// 房间列表
const selectedId = ref(-1);
const roomList = ref<ROOM_LIST_TYPE[]>([]);

// 发送信息
const info = ref('');
const messageList = ref<MESSAGE_TYPE[]>([]);

// 接受信息
const firstRoomText = ref({
  timestamp: '',
  message: '',
});

// 切换用户,清除数据重新获取
const changeUser = () => {
  console.log("切换用户:", userInfo.value);
  selectedId.value = -1;
  messageList.value = [];
  firstRoomText.value = {
    timestamp: '',
    message: '',
  }
}

// 选择房间
const selected = (id: number) => {
  selectedId.value = id;

  const roomListLocal = localStorage.getItem('sharedRoomInfo');
  if (roomListLocal) {
    const rooms = JSON.parse(roomListLocal);
    const room = rooms.find((r: ROOM_LIST_TYPE) => r.id === id);

    // 加入房间
    if (connect.value) {
      messageList.value = [];

      socket.emit('join room', userInfo.value, room, (ack: { success: boolean, room: any, message: any }) => {
        if (ack.success) {
          console.log(`成功加入房间`, ack.room);
          messageList.value = ack.message;

        } else {
          console.error("加入失败:");
        }
      })
    } else {
      console.error("连接失败，无法加入失败");
    }

  }
}


function handleStorage(event: any) {
  if (event.key === "sharedRoomInfo") {
    try {
      const rooms = JSON.parse(event.newValue || "[]");
      roomList.value = rooms;
    } catch (e) {
      console.error("解析出错:", e);
    }
  }
}

onMounted(() => {
  socket.on("connect", () => {
    connect.value = true;
  })

  socket.on("connect_error", (err) => {
    connect.value = false;
  });

  socket.on("disconnect", (reason) => {
    console.warn("断开连接:", reason);
    connect.value = false;
  });

  socket.on("error", (err) => {
    console.error("服务端错误:", err);
    connect.value = false;
  });

  // 从localStorage加载初始数据
  const storedRooms = localStorage.getItem('sharedRoomInfo');
  if (storedRooms) {
    roomList.value = JSON.parse(storedRooms);
  }

  // 监听storage事件以同步数据
  window.addEventListener('storage', handleStorage);


  socket.on('systemMessage', (info) => {
    console.log("收到信息", info);

    firstRoomText.value = {
      timestamp: info.createTime,
      message: info.message
    }
  });


})

onBeforeUnmount(() => {
  window.removeEventListener("storage", handleStorage);
});


// 发送信息
const sendInfo = () => {

  const messageInfo = {
    id: Math.random().toLocaleString(),
    content: info.value,
    timestamp: new Date().toLocaleString(),
    user: {
      id: userInfo.value?.id,
      name: userInfo.value?.name,
      avatar: userInfo.value?.avatar,
    },
    isSuccess: connect.value
  }

  messageList.value.push(messageInfo);
  info.value = '';

  if (connect.value) {
    socket.emit('room message', messageInfo, selectedId.value);
  }
}

/**
 * 创建房间
 */
const createRoom = () => {

  const RoomInfo = {
    id: Math.random(),
    title: '房间名字',
    avatar: 'https://avatars.githubusercontent.com/u/24469566?v=4',
    desc: '房间描述',
    timestamp: new Date().toLocaleString(),
  }

  // 获取当前存储的房间信息数组
  const storedRooms = localStorage.getItem('sharedRoomInfo');
  let rooms = storedRooms ? JSON.parse(storedRooms) : [];

  // 添加新房间信息到数组
  rooms.push(RoomInfo);
  setSharedRoomInfo(rooms);

}

</script>

<style scoped>
.button-theme {
  display: flex;
  align-items: center;
}

.button-theme button:hover {
  opacity: .8;
}

.button-theme button {
  color: #fff;
  outline: none;
  cursor: pointer;
  border-radius: 4px;
  padding: 6px 12px;
  margin-left: 10px;
  border: none;
  font-size: 14px;
  transition: .3s;
  vertical-align: middle;
}

.button-theme .button-light {
  background: #fff;
  border: 1px solid #46484e;
  color: #46484e;
}

.button-theme .button-dark {
  background: #1c1d21;
  border: 1px solid #1c1d21;
}

.container {
  height: calc(100vh - 80px);
  width: 100%;
}

.container-header {
  display: flex;
  justify-content: space-between;
}

.container-header .header {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.header-title {
  margin-right: 10px;
  font-size: 14px;
  color: #46484e;
}


/* 聊天框 */
::v-deep .container-content {
  display: flex;
  flex-direction: row;
  padding: 0;
}

.room-sider {
  display: flex;
  flex-flow: column;
  flex: 0 0 25%;
  min-width: 260px;
  max-width: 500px;
  border-right: 1px solid #e1e4e8;
}

.left-sider-header {
  padding: 15px;
  display: flex;
  align-items: center
}

.left-sider-header ::v-deep .t-input {
  border-radius: 20px
}

.room-list {
  flex: 1;
  max-width: 100%;
  padding: 0 10px 5px;
  overflow-y: auto;
}

/* 聊天室右侧-内容 */

.room-input-main {
  display: flex;
  flex-direction: column;
  flex: 1 1 auto;
}

.room-input-header {

  display: flex;
  align-items: center;
  height: 64px;
  width: 100%;
  z-index: 10;
  margin-right: 1px;
  border-bottom: 1px solid #e1e4e8;
}

.input-header-title {
  padding-left: 15px;
}

.room-input-history {
  flex: 1;
  padding: 0 10px 5px;
  overflow-y: auto;
  min-height: 640px;
  max-height: calc(100vh - 100px);
}

.room-info {
  padding: 10px;
  font-size: 16px;
}

.room-input-message {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  height: 34px;
  border-top: 1px solid #e1e4e8;
}

.input-message ::v-deep .t-input {
  border-radius: 20px
}

.room-input-button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-left: 15px;
}
</style>
